from PIL import Image
import os
import os
import tqdm

def get_filelist_by_data(image_root):
    os.chdir(image_root)
    files = filter(os.path.isfile, os.listdir(image_root))
    files = [os.path.join(image_root, f) for f in files]  # add path to each file
    files.sort(key=lambda x: os.path.getmtime(x))
    #print(files)
    return files

def open_images(image_root):
    imageList = []
    files = get_filelist_by_data(image_root)
    for file in tqdm.tqdm(files):
        if file.split(".")[1]=="jpg":
            path = os.path.join(image_root,file)
            #print(path)
            image = Image.open(path)
            #image.convert('RGB')
            imageList.append(image)
    return imageList , imageList[0]


def  batch_folder2pdf(folders_path):
    for file in tqdm.tqdm(os.listdir(folders_path)):
        folder = os.path.join(folders_path,file)
        try:
            folder2pdf(folder,file,folders_path)
        except Exception as e:
            print(e)


def folder2pdf(folder, filename , save_path):
    imageList , image1 = open_images(folder)
    save_path = os.path.join(save_path,filename + ".pdf")
    image1.save( save_path,  save_all=True, append_images=imageList)
    print('save_path:{}'.format(save_path,filename))

if __name__ == '__main__':

    #folders_path = "/Users/leslie/Desktop/"  #folder1 folder2 ... every folder contains a book
    #batch_folder2pdf(folders_path)

    folder_path = "/Users/leslie/Desktop/1"
    folder2pdf(folder_path,folder_path.split("/")[-1],"/Users/leslie/Desktop/")

